import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import './style.css'

// 子应用路由
const routes = [
  {
    path: '/',
    component: () => import('./views/Home.vue')
  },
  {
    path: '/detail',
    component: () => import('./views/Detail.vue')
  }
]

let router = null
let instance = null
let history = null

// 渲染函数
function render(props = {}) {
  const { container, name } = props
  
  // 在乾坤环境下运行需要特殊处理
  if (window.__POWERED_BY_QIANKUN__) {
    // 路由基础路径需要加上应用名
    history = createWebHistory(`/${name}`)
  } else {
    history = createWebHistory()
  }
  
  router = createRouter({
    history,
    routes
  })
  
  // 创建 Vue 实例
  instance = createApp(App)
  instance.use(router)
  
  // 挂载应用
  const appContainer = container ? container.querySelector('#app') : '#app'
  instance.mount(appContainer)
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

// 导出乾坤生命周期钩子
export async function bootstrap() {
  console.log('vue app bootstraped')
}

export async function mount(props) {
  console.log('vue app mounted', props)
  render(props)
}

export async function unmount() {
  console.log('vue app unmounted')
  instance.unmount()
  instance = null
  router = null
  history = null
}